package com.steam.exception;

import com.steam.enums.GlobalExceptionCode;
import com.steam.result.JSONResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public JSONResult customException(Exception e){
        e.printStackTrace();
        log.error("全局统一异常捕捉到错误，错误类型为Exception，错误信息为：{}", e.getMessage());
        // return JSONResult.error(GlobalExceptionCode.ERROR.getMessage(), GlobalExceptionCode.ERROR.getCode());
        return JSONResult.error(GlobalExceptionCode.ERROR);
    }


    @ExceptionHandler(GlobalCustomException.class)
    public JSONResult customException(GlobalCustomException e){
        e.printStackTrace();
        log.error("全局统一异常捕捉到错误，错误类型为GlobalCustomException，错误信息为：{}", e.getMessage());
        // return JSONResult.error(GlobalExceptionCode.ERROR.getMessage(), GlobalExceptionCode.ERROR.getCode());
        return JSONResult.error(e);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public JSONResult customException(MethodArgumentNotValidException e){
        e.printStackTrace();
        log.error("全局统一异常捕捉到错误，错误类型为MethodArgumentNotValidException，错误信息为：{}", e.getMessage());
        // return JSONResult.error(GlobalExceptionCode.ERROR.getMessage(), GlobalExceptionCode.ERROR.getCode());
        StringBuffer sb = new StringBuffer();
        e.getBindingResult().getAllErrors().forEach(obj->{
            sb.append(obj.getDefaultMessage()).append(",");
        });
        return JSONResult.error(sb.toString(), "1000");
    }


}
